#coding=utf-8
from uliweb import expose
from uliweb.orm import get_model,Begin,Commit,Rollback


def __begin__():
    """
    用户验证 权限验证
    """
    from uliweb import functions
    functions.require_login()
    return functions.has_role()

@expose('/myrbac')
class MyRbac(object):
    def __init__(self):
        self.menurolemodel = get_model('menurole')
        self.usermodel = get_model('user')
        self.menumodel = get_model('menu')
        self.permissionmodel = get_model('permission')
        self.rolemodel = get_model('role')

    def __begin__(self):
        if not request.user.is_superuser:
            error('你不是超级用户不能进行这项操作！')

    def menurole(self):
        """
        菜单权限
        """
        return {}


    def menuroleadd(self):
        """
        添加菜单权限
        """
        return{}

    def menuroleedit(self):
        """
        编辑菜单权限
        """
        return{}

    def menurolesave(self):
        """
        保存菜单权限
        """
        _id = request.POST.get('id')
        name = request.POST.get('role_name')
        description = request.POST.get('role_desc')

        users = request.POST.getlist('usersid')

        if _id == None:
            orm_data = self.menurolemodel(name=name,
                                          description=description
                                          )

        else:
            orm_data = functions.get_object(self.menurolemodel, int(_id), cache=True, use_local=True)
            #update操作
            orm_data.name=name
            orm_data.description=description



        Begin()

        try:
            orm_data.save()

            orm_data.users.remove()
            for i in users:

                user = self.usermodel.get(int(i))
                orm_data.users.add(user)

            Commit()
            return json({"success":200,"msg":"添加成功"}) 

        except:
            Rollback()
            return json({"error":500,"msg":"已经有同名存在"})

    def menuroledel(self):
        """
        删除菜单权限
        """

        _id = request.POST.get('id')
        usersid = request.POST.get('usersid')
        menusid = request.POST.get('menusid')

        mid = []
        for i in _id.split(','):
            #mid.append(int(i))
            menurole = self.menurolemodel.get(int(i))
            for j in usersid.split(','):
                user = self.usermodel.get(int(j))
                if menurole.users.has(user):
                    menurole.users.remove(user)
            for k in menusid.split(','):
                menu = self.menumodel.get(int(k))
                if menurole.menus.has(menu):
                    menurole.menus.remove(menu)

            menurole.delete()

        #self.menurolemodel.filter(self.menurolemodel.c.id.in_(mid)).remove()
        return json({"success":True,"msg":"删除成功"})

    def menurolemenugrant(self):
        """
        菜单授权
        """
        _id = request.GET.get("id")

        return{"role_id":_id}

    def getmenurolemenu(self):
        """
        返回菜单角色应有的菜单名
        """
        #菜单权限ID
        menurole_id = request.POST.get("id")

        menurole = functions.get_object(self.menurolemodel, int(menurole_id), cache=True, use_local=True)

        menus_id = []

        for i in menurole.menus:
            menus_id.append({"id":i.id,
                             "text":i.menuname,
                             "attributes":{"url":i.menuurl},
                             "iconCls":i.menuicon,
                             'parent_id':i.pid
                             })

        return json(menus_id)

    def menurolemenussave(self):
        """
        保存菜单角色的菜单权限
        """
        _id = request.POST.get('id')
        menus = request.POST.get('ids')
        error_menus = []

        menurole = self.menurolemodel.get(int(_id))
        menurole.menus.remove()
        for i in menus.split(','):
            menu = self.menumodel.get(int(i))
            menurole.menus.add(menu)

        return json({"success":200,"msg":"添加成功"})

    def permission(self):
        """
        操作权限
        """
        return {}

    def permissionadd(self):
        """
        添加操作权限
        """
        return{}

    def permissionedit(self):
        """
        编辑操作权限
        """
        _id = request.GET.get('id')
        orm_data = functions.get_object(self.permissionmodel, int(_id), cache=True, use_local=True)
        return{"id":orm_data.id,
               "name":orm_data.name,
               "pid":orm_data.pid,
               "resourcetype":orm_data.resourcetype,
               "url":orm_data.url,
               "description":orm_data.description
               }

    def permissionsave(self):
        """
        保存操作权限
        """

        _id = request.POST.get('id')
        name = request.POST.get('name')
        url = request.POST.get('url')
        pid = request.POST.get('pid')
        resourcetype = request.POST.get('resourcetype')
        description = request.POST.get('description')

        #默认为菜单
        if resourcetype == None:
            resourcetype = 1

        if url != None:
            url = url.strip()

        if _id == None:
            orm_data = self.permissionmodel(name=name,
                                            pid=pid,
                                            resourcetype=resourcetype,
                                            description=description,
                                            url=url
                                            )

        else:
            orm_data = functions.get_object(self.permissionmodel, int(_id), cache=True, use_local=True)
            #update操作
            orm_data.name=name
            orm_data.url=url
            orm_data.pid=pid
            orm_data.resourcetype=resourcetype
            orm_data.description=description

        try:
            orm_data.save()
            return json({"success":200,"msg":"添加成功"}) 
        except:
            return json({"error":500,"msg":"已经有同名存在"})


    def permissiondel(self):
        """
        删除操作权限,同时删除管理子菜单
        """

        _id = request.POST.get('id')           

        self.permissionmodel.filter(self.permissionmodel.c.id == int(_id)).remove()
        self.permissionmodel.filter(self.permissionmodel.c.pid == int(_id)).remove()
        return json({"success":True,"msg":"删除成功"})

    def role(self):
        """
        操作角色
        """
        return {}

    def roleadd(self):
        """
        添加操作角色
        """
        return{}

    def roleedit(self):
        """
        编辑操作角色
        """
        return{}

    def rolesave(self):
        """
        保存菜单权限
        """
        _id = request.POST.get('id')
        name = request.POST.get('name')
        description = request.POST.get('description')

        users = request.POST.getlist('usersid')

        if _id == None:
            orm_data = self.rolemodel(name=name,
                                      description=description
                                      )

        else:
            orm_data = functions.get_object(self.rolemodel, int(_id), cache=True, use_local=True)
            #update操作
            orm_data.name=name
            orm_data.description=description



        Begin()

        try:
            orm_data.save()

            orm_data.users.remove()
            for i in users:

                user = self.usermodel.get(int(i))
                orm_data.users.add(user)

            Commit()
            return json({"success":200,"msg":"添加成功"}) 

        except:
            Rollback()
            return json({"error":500,"msg":"已经有同名存在"})

    def roledel(self):
        """
        删除菜单权限
        """
    
        _id = request.POST.get('id')
        usersid = request.POST.get('usersid')
        permissionsid = request.POST.get('permissionsid')
    
        mid = []
        for i in _id.split(','):
            #mid.append(int(i))
            role = self.rolemodel.get(int(i))
            for j in usersid.split(','):
                user = self.usermodel.get(int(j))
                if role.users.has(user):
                    role.users.remove(user)
            for k in permissionsid.split(','):
                permission = self.permissionmodel.get(int(k))
                if role.permissions.has(permission):
                    role.permissions.remove(permission)
    
            menurole.delete()
    
        #self.menurolemodel.filter(self.menurolemodel.c.id.in_(mid)).remove()
        return json({"success":True,"msg":"删除成功"})
    
    
    def rolepermissionsgrant(self):
        """
        角色授权
        """
        _id = request.GET.get("id")

        return{"role_id":_id}
    
    def getrolepermission(self):
        """
        返回角色应有的权限名
        """
        #菜单权限ID
        _id = request.POST.get("id")

        role = functions.get_object(self.rolemodel, int(_id), cache=True, use_local=True)

        permissions_id = []

        for i in role.permissions:
            permissions_id.append({"id":i.id,
                             "text":i.name,
                             "attributes":{"url":i.url},
                             'parent_id':i.pid,
                             'pid':i.pid,
                             })

        return json(permissions_id)

    def rolepermissionssave(self):
        """
        保存角色的权限
        """
        _id = request.POST.get('id')
        permissions = request.POST.get('ids')
        error_permissions = []

        role = self.rolemodel.get(int(_id))
        role.permissions.remove()
        for i in permissions.split(','):
            permission = self.permissionmodel.get(int(i))
            role.permissions.add(permission)

        return json({"success":200,"msg":"添加成功"})